package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"srv/model/es"
	"srv/model/mysql"
	"strconv"
	"sync"

	"srv/internal/svc"
	"srv/renrenzu"

	"github.com/zeromicro/go-zero/core/logx"
)

type SyncGoodsEsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSyncGoodsEsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SyncGoodsEsLogic {
	return &SyncGoodsEsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SyncGoodsEsLogic) SyncGoodsEs(in *renrenzu.SyncGoodsEsRequest) (*renrenzu.SyncGoodsEsResponse, error) {
	// todo: add your logic here and delete this line
	var (
		list []*mysql.Goods
		wg   sync.WaitGroup
	)
	mysql.DB.Find(&list)
	fmt.Println(list)
	for _, v := range list {
		wg.Add(1)

		go func(goods *mysql.Goods) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(goods)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "goods",
				DocumentID: strconv.Itoa(int(goods.ID)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), es.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(v)
	}
	wg.Wait()
	return &renrenzu.SyncGoodsEsResponse{}, nil
}
